package com.ruoyi.business.service.impl;

import com.ruoyi.business.service.IProcessService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * Created by lanxw
 */
@Service
public class ProcessServiceImpl implements IProcessService {
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Override
    public Deployment deploy(String filePath) throws IOException {
        Deployment deploy = null;
        if (filePath.endsWith("zip")) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(filePath));
            deploy = repositoryService.createDeployment()
                    .addZipInputStream(zipInputStream)
                    .deploy();
        } else if (filePath.endsWith("bpmn")) {
            deploy = repositoryService.createDeployment()
                    .addInputStream(filePath,new FileInputStream(filePath))
                    .deploy();
        }
        return deploy;
    }

    @Override
    public ProcessDefinition selectProcessDefinitionByDeploymentId(String deploymentId) {
        return repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();
    }

    @Override
    public InputStream getResourceAsStream(String deploymentId, String resourceName) {
        return repositoryService.getResourceAsStream(deploymentId,resourceName);
    }

    @Override
    public InputStream getProcessImage(String processDefinitionId,
                                      List<String> highLightedActivities,
                                      List<String> highLightedFlows) {
    BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
    ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
    //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
    InputStream inputStream = generator.generateDiagram(model, highLightedActivities, highLightedFlows,"宋体","宋体","宋体");
    return inputStream;
}

    @Override
    public ProcessInstance startProcessInstanceByKey(String definitionKey, String businessKey, Map<String, Object> variables) {
        return runtimeService.startProcessInstanceByKey(definitionKey,businessKey,variables);
    }

    @Override
    public Task getTaskByInstanceId(String instanceId) {
        return taskService.createTaskQuery().processInstanceId(instanceId).singleResult();
    }

    @Override
    public void addCandidateUser(String taskId, String candidateUser) {
        taskService.addCandidateUser(taskId,candidateUser);
    }

    @Override
    public ProcessInstance getProcessInstanceById(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public List<String> getActiveActivityIds(String processInstanceId) {
        return runtimeService.getActiveActivityIds(processInstanceId);
    }

    @Override
    public void deleteProcessInstance(String instanceId, String reason) {
        runtimeService.deleteProcessInstance(instanceId,reason);
    }

    @Override
    public long selectTodoTaskCount(String definitionKey, String candidateUser) {
        return taskService.createTaskQuery()
                .processDefinitionKey(definitionKey)
                .taskCandidateUser(candidateUser)
                .count();
    }

    @Override
    public List<Task> selectTodoTaskList(String definitionKey, String candidateUser,Integer firstResult,Integer pageSize) {
        return taskService.createTaskQuery()
                .processDefinitionKey(definitionKey)
                .taskCandidateUser(candidateUser)
                .orderByTaskCreateTime()
                .desc()
                .listPage(firstResult,pageSize);
    }

    @Override
    public Task getTaskByTaskId(String taskId) {
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    @Override
    public void claimAndComplateTask(Task task, String userId, boolean auditStatusBoolean, String commentStr) {
        String taskId = task.getId();
        taskService.addComment(taskId,task.getProcessInstanceId(),commentStr);
        taskService.claim(taskId, userId);
        taskService.setVariable(taskId,task.getTaskDefinitionKey(),auditStatusBoolean);
        taskService.complete(taskId);
    }

    @Override
    public void setVariable(String taskId, String variableName, long variableValue) {
        taskService.setVariable(taskId,variableName,variableValue);
    }

    @Override
    public long selectDoneTaskCount(String definitionKey, String userId) {
        return historyService
                .createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .count();
    }

    @Override/*第三步,和之前的carPackageAudit相似*/
    public List<HistoricTaskInstance> selectDoneTaskList(String definitionKey, String userId, Integer firstResult, Integer pageSize) {
        return historyService
                .createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .listPage(firstResult,pageSize);
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) {
        return historyService
                .createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
    }

    @Override
    public List<HistoricActivityInstance> selectHistoryTaskList(String instanceId) {

        return historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceId)
                .activityType("userTask")/*第10步:不加会报格式转换异常*/
                .finished()
                .orderByHistoricActivityInstanceStartTime()
                .desc()
                .list();
    }

    @Override/*第9步:查备注信息,拼第0个*/

    public String getTaskComment(String taskId) {
        List<Comment> taskComments = taskService.getTaskComments(taskId, "comment");
        if(taskComments!=null && taskComments.size()>0){
            return taskComments.get(0).getFullMessage();
        }else{
            return "";
        }
    }
}
